package com.example.backend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.example.backend.common.ResultMessage;
import com.example.backend.entity.ShangJia;
import com.example.backend.service.IShangJiaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@CrossOrigin
@RequestMapping("/shangjia")
public class ShangJiaController {
    @Autowired
    private IShangJiaService shangJiaService;

    @PostMapping
    public ResultMessage addShangJia(@RequestBody ShangJia shangJia){
        if (shangJiaService.addShangJia(shangJia)){
            return ResultMessage.success(shangJia,"新增成功");
        }
        return ResultMessage.error("新增失败");
    }

    @DeleteMapping("/{sjid}")
    public ResultMessage deleteShangJia(@PathVariable Integer sjid){
        if (shangJiaService.deleteShangJia(sjid)){
            return ResultMessage.success(null,"删除成功");
        }
        return ResultMessage.error("删除失败");
    }

    @PutMapping
    public ResultMessage updateShangJia(@RequestBody ShangJia shangJia){
        System.err.println(shangJia);
        if (shangJiaService.updateShangJia(shangJia)){
            return ResultMessage.success(shangJia,"修改成功");
        }
        return ResultMessage.error("修改失败");
    }

    //@GetMapping
    //public ResultMessage queryShangJia(){
    //    return ResultMessage.success(shangJiaService.queryShangJia(),"查询成功");
    //}

    // 新增：分页查询接口
    @GetMapping("/list")
    public ResultMessage queryShangJiaByPage(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size,
            @RequestParam(required = false) String sortField,
            @RequestParam(required = false) String sortOrder,
            ShangJia shangJia) {

        // 调用分页查询方法（需要在 Service 中实现）
        Page<ShangJia> pageResult = shangJiaService.queryShangJiaByPage(
                shangJia, page, size, sortField, sortOrder);

        return ResultMessage.success(pageResult, "查询成功");
    }

    @GetMapping("/id/{sjid}")
    public ResultMessage queryShangJiaById(@PathVariable Integer sjid){
        return ResultMessage.success(shangJiaService.queryShangJiaById(sjid),"查询成功");
    }

    @GetMapping
    public ResultMessage queryShangJiaByName(@RequestParam String name) {
        return ResultMessage.success(shangJiaService.queryShangJiaByName(name), "查询成功");
    }

    @GetMapping("/all")
    public ResultMessage queryShangJia() {
        return ResultMessage.success(shangJiaService.queryShangJiaList(), "查询成功");
    }

   @GetMapping("/yhid/{yhid}")
    public ResultMessage queryShangJiaByYhid(@PathVariable Integer yhid) {
        return ResultMessage.success(shangJiaService.queryShangJiaByYhid(yhid), "查询成功");
    }

}
